package net.diaowen.dwsurvey.service.impl;

import net.diaowen.common.base.entity.User;
import net.diaowen.common.service.BaseServiceImpl;
import net.diaowen.common.utils.weixin.WeChatUtil;
import net.diaowen.dwsurvey.dao.SurveyGroupDao;
import net.diaowen.dwsurvey.entity.SurveyDirectory;
import net.diaowen.dwsurvey.entity.SurveyGroup;
import net.diaowen.dwsurvey.service.SurveyDirectoryManager;
import net.diaowen.dwsurvey.service.SurveyGroupManager;
import net.diaowen.dwsurvey.service.UserManager;
import net.sf.json.JSONObject;
import org.hibernate.criterion.Criterion;
import org.hibernate.criterion.Restrictions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.List;


/**
 * 分组管理
 * @author zhangyuting
 * @date 2019年5月8日
 *
 */
@Service
public class SurveyGroupManagerImpl extends BaseServiceImpl<SurveyGroup, String> implements SurveyGroupManager {
	
	@Autowired
	private UserManager userManager;
	@Autowired
	private SurveyDirectoryManager surveyDirectoryManager;
	
	
	@Override
	public void adminSave(String surveyId,String groupId) {
		List<SurveyGroup> list = findListBySurveyId(surveyId);
		if (list.size() > 0) {
			for (SurveyGroup sg : list) {
				delete(sg.getId());
			}
		}
		String[] groupIds = groupId.split("#");
		ArrayList<String> groupIdsList = new ArrayList<String>(Arrays.asList(groupIds)) ;
		for(String s : groupIdsList) {
			if (!s.equals("")) {
				SurveyGroup surveyGroup = new SurveyGroup();
				surveyGroup.setSurveyId(surveyId);
				surveyGroup.setGroupId(s);
				save(surveyGroup);
			}
		}
	}
	
	@Override
	public void removeBySurveyId(String surveyId){
		List<SurveyGroup> list = findListBySurveyId(surveyId);
		if (list.size() > 0) {
			for (SurveyGroup sg : list) {
				delete(sg.getId());
			}
		}
	}

	@Autowired
	private SurveyGroupDao surveyGroupDao;

	@Override
	public void setBaseDao() {
		this.baseDao= surveyGroupDao;
	}

	@Override
	public List<SurveyGroup> findListBySurveyId(String surveyId) {
		Criterion criterion=Restrictions.eq("surveyId", surveyId);
		return findList(criterion);
	}

	@Override
	public boolean checkGroupPermission(String surveyId,String studentId) {
		// 先获取orgid,orgid取发卷人的orgid
		SurveyDirectory survey = surveyDirectoryManager.getSurvey(surveyId);
		String orgId = userManager.get(survey.getUserId()).getOrgId();
		
		// 先检查有没有这个用户，没有这个用户不行
		User userStudent = userManager.findLoginName(orgId + "_" + studentId);
		if (userStudent == null) {
			return false;
		}
		//先检查是否按小组发卷,如果没有就返回true，谁都可以答
		List<SurveyGroup> sgList = findListBySurveyId(surveyId);
		if (sgList == null || sgList.size() == 0) {
			return true;
		}
		//如果按小组发卷了，那么检查用户是否在小组中，如果在就返回true，可以作答
		Long count = getCountBySurveyIdAndStudentId(surveyId,orgId, studentId);
		if (count > 0 ) {
			return true;
		} else {
			return false;
		}

	}

	@Override
	public List<SurveyGroup> findListByGroupId(String groupId) {
		Criterion criterion=Restrictions.eq("groupId", groupId);
		return findList(criterion);
	}
	
	@Override
	public Long getCountBySurveyIdAndStudentId(String surveyId,String orgId, String studentId) {
		String hql = "select  count(*) from SurveyGroup tsg , UserGroup tug , User tu where tsg.groupId = tug.usergroupId and  tu.id = tug.userId  and tsg.surveyId = ? and tu.orgId = ? and tu.studentId=?";
		Long count = (Long) surveyGroupDao.findUniObjs(hql, surveyId,orgId, studentId);
		return count;
	}


	@Override
	public List<Object[]> getGroupWinUser(String surveyId) {
		String hql = "select wxId from WcUser where userId in ( select userId from UserGroup where usergroupId = ? )";
		List<Object[]> usrMap = surveyGroupDao.findList(hql, surveyId);
		return usrMap;
	}

	@Override
	public void sendWixinNotify(String openId,String userName,String surveyName) {

		//消息模板或客服消息推送给orgOpenId 目前采用客服模式
		String requestUrl = "https://api.weixin.qq.com/cgi-bin/message/template/send?access_token="+ WeChatUtil.getAccessToken().getToken();

		//String requestUrl = "https://api.weixin.qq.com/cgi-bin/message/template/send?access_token=";

		SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");

		String outputStr ="{"
				+"\"data\":{"
				+"\"first\":{"
				+"\"color\":\"#000000\","
				+"\"value\":\"您有一个问卷《"+surveyName+"》需要完成\""
				+"},"
				+"\"keyword1\":{"
				+"\"color\":\"#000000\","
				+"\"value\":\""+userName+"\""
				+"},"
				+"\"keyword2\":{"
				+"\"color\":\"#000000\","
				+"\"value\":\""+userName+"\""
				+"},"
				+"\"keyword3\":{"
				+"\"color\":\"#000000\","
				+"\"value\":\""+df.format(new Date())+"\""
				+"},"
				+"\"keyword4\":{"
				+"\"color\":\"#000000\","
				+"\"value\":\"请及时填写问卷,谢谢！\""
				+"},"
				+"\"remark\":{"
				+"\"color\":\"#000000\","
				+"\"value\":\"无\""
				+"}"
				+"},"
				// +"\"template_id\":\"Y1Z_rmj8eN8E0-M3JOHrMRxGZ4oomGmCex4uUosMDak\","//测试模板
				+"\"template_id\":\"4lXZFzFWB3hdVKLgmLdvMA6b8jRXOHS17aMAAISuSdw\","
				+"\"touser\":\""+openId+"\","
				// +"\"url\":\"https://open.weixin.qq.com/connect/oauth2/authorize?appid=wx2c27e6ac1c22e88d&redirect_uri=http://wctest.bbchina.cn/wexin/bind.do&response_type=code&scope=snsapi_base&state=0#wechat_redirect\""
				+"\"url\":\"https://open.weixin.qq.com/connect/oauth2/authorize?appid=wx9eb297155d4cdc7e&redirect_uri=http://survey.acbsp.cn/wexin/bind.do&response_type=code&scope=snsapi_base&state=0#wechat_redirect\""
				+"}";
		System.out.println("openId = " + openId);

		JSONObject temp=WeChatUtil.httpRequest(requestUrl, "POST", outputStr);
		System.out.println("temp"+temp);
		System.out.println("temp.toString()"+temp.toString());

	}

    @Override
    public void sendGroupWixinNotify(String toUser, String userName, String getNotifications) {
		//消息模板或客服消息推送给orgOpenId 目前采用客服模式
		String requestUrl = "https://api.weixin.qq.com/cgi-bin/message/template/send?access_token="+ WeChatUtil.getAccessToken().getToken();
		SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");

		String outputStr ="{"
				+"\"data\":{"
				+"\"first\":{"
				+"\"color\":\"#000000\","
				+"\"value\":\"您有一个 通知 需要查看\""
				+"},"
				+"\"keyword1\":{"
				+"\"color\":\"#000000\","
				+"\"value\":\""+userName+"\""
				+"},"
				+"\"keyword2\":{"
				+"\"color\":\"#000000\","
				+"\"value\":\""+userName+"\""
				+"},"
				+"\"keyword3\":{"
				+"\"color\":\"#000000\","
				+"\"value\":\""+df.format(new Date())+"\""
				+"},"
				+"\"keyword4\":{"
				+"\"color\":\"#000000\","
				+"\"value\":\"请点击查看通知！\""
				+"},"
				+"\"remark\":{"
				+"\"color\":\"#000000\","
				+"\"value\":\"无\""
				+"}"
				+"},"
				// +"\"template_id\":\"Y1Z_rmj8eN8E0-M3JOHrMRxGZ4oomGmCex4uUosMDak\","//测试模板
				+"\"template_id\":\"4lXZFzFWB3hdVKLgmLdvMA6b8jRXOHS17aMAAISuSdw\","
				+"\"touser\":\""+toUser+"\","
				// +"\"url\":\"https://open.weixin.qq.com/connect/oauth2/authorize?appid=wx2c27e6ac1c22e88d&redirect_uri=http://wctest.bbchina.cn/wexin/bind.do&response_type=code&scope=snsapi_base&state=0#wechat_redirect\""
				+"\"url\":\"https://open.weixin.qq.com/connect/oauth2/authorize?appid=wx9eb297155d4cdc7e&redirect_uri=http://survey.acbsp.cn/wexin/particulars.do?notice="+getNotifications+"&response_type=code&scope=snsapi_base&state=0#wechat_redirect\""
				+"}";

		System.out.println("outputStr = " + outputStr);
		// ("getNotifications",getNotifications);

		JSONObject temp=WeChatUtil.httpRequest(requestUrl, "POST", outputStr);
		System.out.println("temp"+temp);
		System.out.println("temp.toString()"+temp.toString());
	}
}
